<template>
  <div class="lb-company-add">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="page-main">
      <lb-classify-title title="基本信息"></lb-classify-title>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="basicForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item label="公司名称" prop="name">
          <el-input
            v-model="subForm.name"
            placeholder="请输入公司名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司简称" prop="short_name">
          <el-input
            v-model="subForm.short_name"
            placeholder="请输入公司简称"
            :maxlength="6"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="公司地址" prop="addr">
          <el-input
            v-model="subForm.addr"
            placeholder="请输入公司地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司logo" prop="logo">
          <lb-cover
            :fileList="subForm.logo"
            @selectedFiles="getLogo($event, 'logo')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 133 * 133</lb-tool-tips>
        </el-form-item>
      </el-form>

      <lb-classify-title title="相关信息"></lb-classify-title>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="relevantForm"
        :inline="true"
        label-width="100px"
        class="relevant-form"
      >
        <el-form-item label="公司经度" prop="longitude">
          <el-input
            v-model="subForm.longitude"
            placeholder="请输入公司经度"
          ></el-input>
        </el-form-item>
        <el-form-item label="公司纬度" prop="latitude">
          <el-input
            v-model="subForm.latitude"
            placeholder="请输入公司纬度"
          ></el-input>
        </el-form-item>
        <lb-button
          type="primary"
          class="getLocation"
          size="mini"
          plain
          @click="showMap = true"
          >获取公司坐标</lb-button
        >
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item label="免审口令" prop="auth_code">
          <el-input
            v-model="subForm.auth_code"
            placeholder="请输入免审口令"
          ></el-input>
          <lb-tool-tips>{{ tips[1] }}</lb-tool-tips>
        </el-form-item>
      </el-form>

      <lb-classify-title title="图片信息"></lb-classify-title>
      <el-form
        @submit.native.prevent
        :model="subForm"
        :rules="subFormRules"
        ref="imgForm"
        label-width="180px"
        class="basic-form"
      >
        <el-form-item :label="tips[2]" prop="desc">
          <lb-cover
            :fileList="subForm.desc"
            @selectedFiles="getLogo($event, 'desc')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 423</lb-tool-tips>
        </el-form-item>
        <!-- 官网轮播 -->
        <el-form-item
          :label="tips[3]"
          prop="culture"
          v-if="routesItem.app_model_name !== 'longbing_decorate'"
        >
          <lb-cover
            type="more"
            :fileList="subForm.culture"
            @selectedFiles="selectedFiles($event, 'culture')"
            @moveFiles="moveFiles($event, 'culture')"
          ></lb-cover>
          <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
        </el-form-item>
        <el-form
          @submit.native.prevent
          :model="subForm"
          :rules="banquetFormRules"
          ref="banquetForm"
          label-width="180px"
          class="basic-form"
          v-if="base_plug.banquet_auth"
        >
          <el-form-item :label="tips[4]" prop="background_map">
            <lb-cover
              :fileList="subForm.background_map"
              @selectedFiles="getLogo($event, 'background_map')"
            ></lb-cover>
            <lb-tool-tips>图片建议尺寸: 750 * 400</lb-tool-tips>
          </el-form-item>
          <el-form-item label="营业时间" prop="business_hours">
            <el-input
              v-model="subForm.business_hours"
              placeholder="请输入营业时间"
            ></el-input>
            <lb-tool-tips>例如：周一至周五 9：00-16:00</lb-tool-tips>
          </el-form-item>
          <el-form-item label="联系电话" prop="banquet_mobile">
            <el-input
              v-model="subForm.banquet_mobile_code"
              maxlength="10"
              placeholder="区号"
              style="width: 60px"
            ></el-input>
            -
            <el-input
              v-model="subForm.banquet_mobile"
              maxlength="20"
              placeholder="请输入联系电话"
              style="width: 223px"
            ></el-input>
            <lb-tool-tips>请输入准确的电话号码，便于买家联系商家</lb-tool-tips>
          </el-form-item>
          <el-form-item label="管理员" prop="staff_id" v-if="subForm.id">
            <el-select v-model="subForm.staff_id" filterable clearable>
              <el-option
                v-for="item in base_staff"
                :key="item.fans_id"
                :label="item.name"
                :value="item.fans_id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="服务标签" prop="service_tag">
            <div
              class="mb-lg"
              v-for="(item, index) in subForm.service_tag"
              :key="index"
            >
              <el-input
                class="mr-sm"
                v-model="item.title"
                placeholder="请输入服务标签"
                maxlength="5"
                show-word-limit
              ></el-input>
              <lb-tool-tips v-if="index === 0"
                >门店服务标签可添加停车方便、免费机麻、茶水免费等词</lb-tool-tips
              >
              <el-button
                size="small"
                type="danger"
                icon="el-icon-delete"
                @click="toAddDel(index, 1)"
                v-if="
                  (subForm.service_tag.length === 1 && index !== 0) ||
                  subForm.service_tag.length > 1
                "
                >{{ $t('action.delete') }}</el-button
              >
              <el-button
                size="small"
                type="primary"
                icon="el-icon-plus"
                v-if="
                  index === subForm.service_tag.length - 1 &&
                  subForm.service_tag.length < 5
                "
                @click="toAddDel(index)"
                >{{ $t('action.add') }}</el-button
              >
            </div>
          </el-form-item>
        </el-form>
        <el-form-item>
          <lb-button type="primary" @click="submitCompanyInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button plain @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
    <lb-map :dialogVisible.sync="showMap" @selectedLatLng="getLatLng"></lb-map>
  </div>
</template>

<script>
import {
  reg
} from '@/utils/reg'
import { mapState } from 'vuex'
export default {
  data () {
    let validateStaff = (rule, value, callback) => {
      if (!this.subForm.id) {
        callback()
      } else if (!value) {
        callback(new Error(`请选择管理员`))
      } else {
        callback()
      }
    }
    let validateTag = (rule, value, callback) => {
      for (let key in value) {
        let index = key * 1 + 1
        let { title } = value[key]
        if (title) {
          title = title.replace(/^\s+|\s+$/g, '')
        }
        if (!title) {
          callback(new Error(`服务标签 第${index}条数据：请输入服务标签`))
          return
        }
      }
      let arr = value.filter(item => {
        return item.title
      })
      if (arr.length === value.length) {
        callback()
      }
    }
    return {
      tips: {
        1: `该公司的免审口令，创建${this.$t(
          'menu.BusinessCard'
        )}时，选择此公司时需要输入此公司对应的免审口令才能加入此公司，如果此免审口令不填，使用${this.$t(
          'menu.BusinessCard'
        )}管理中设置的免审口令也可以加入该公司`,
        2: `${this.$t('menu.Malls')}背景图`,
        3: `${this.$t('menu.Website')}轮播图`,
        4: `${this.$t('menu.Banquet')}背景图`
      },
      navTitle: '',
      showMap: false,
      base_plug: {},
      base_staff: [],
      imgArr: [],
      subForm: {
        id: 0,
        name: '',
        short_name: '',
        addr: '',
        logo: [],
        longitude: '', // 经度
        latitude: '', // 纬度
        top: '',
        auth_code: '',
        desc: [],
        culture: [],
        background_map: [],
        business_hours: '',
        banquet_mobile_code: '',
        banquet_mobile: '',
        service_tag: [{ title: '' }],
        staff_id: ''
      },
      subFormRules: {
        name: { required: true, validator: reg.isNotNull, text: `公司名称`, reg_type: 2, trigger: 'blur' },
        short_name: { required: true, validator: reg.isNotNull, text: `公司简称`, reg_type: 2, trigger: 'blur' },
        addr: { required: true, type: 'string', message: '请输入公司地址', trigger: 'blur' },
        logo: { required: true, type: 'array', message: '请上传封面图片', trigger: 'blur' },
        longitude: { required: true, message: '请输入公司经度', trigger: ['blur', 'change'] },
        latitude: { required: true, message: '请输入公司纬度', trigger: ['blur', 'change'] },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' },
        desc: { required: true, type: 'array', message: `请上传${this.$t('menu.Malls')}背景图`, trigger: 'blur' },
        culture: { required: true, type: 'array', message: `请上传${this.$t('menu.Website')}轮播图`, trigger: 'change' }
      },
      banquetFormRules: {
        background_map: { required: true, type: 'array', message: `请上传场地预约背景图`, trigger: 'blur' },
        business_hours: { required: true, validator: reg.isNotNull, text: `营业时间`, reg_type: 2, trigger: 'blur' },
        banquet_mobile: { required: true, type: 'string', message: '请输入联系电话', trigger: 'blur' },
        service_tag: { required: true, validator: validateTag, trigger: 'blur' },
        staff_id: { required: true, validator: validateStaff, trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id = 0 } = this.$route.query
    this.navTitle = this.$t(id ? 'menu.EditCompany' : 'menu.AddCompany')
    await this.getBaseInfo(id)
    if (id) {
      this.subForm.id = id
      this.getCompanyInfo(id)
    }
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getBaseInfo (id) {
      this.imgArr = ['logo', 'desc', 'background_map']
      let { data: plug } = await this.$api.companyGetPlugAuth()
      this.base_plug = plug
      if (!id) return
      let { data: staff } = await this.$api.getCompanyStaff({ company_id: id })
      this.base_staff = staff
    },
    async getCompanyInfo (id) {
      let { code, data } = await this.$api.getCompanyInfo({ id })
      if (code !== 200) return
      this.imgArr.map(item => {
        data[item] = data[item] ? [{ url: data[item] }] : []
      })
      data.culture = data.culture && data.culture.length > 0 ? data.culture.map(item => {
        return { url: item }
      }) : []

      data.service_tag = data.service_tag && data.service_tag.length > 0 ? data.service_tag.map(item => {
        return { title: item }
      }) : [{ title: '' }]
      if (data.banquet_mobile && data.banquet_mobile.includes(' - ')) {
        let arr = data.banquet_mobile.split(' - ')
        data.banquet_mobile_code = arr[0]
        data.banquet_mobile = arr[1]
      } else {
        data.banquet_mobile = data.banquet_mobile || ''
      }
      data.staff_id = data.staff_id ? data.staff_id : ''
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    /**
     * @method 获取logo
     */
    getLogo (img, key) {
      this.subForm[key] = img
    },
    selectedFiles (imgs, key) {
      this.subForm[key].push(...imgs)
    },
    moveFiles (imgs, key) {
      this.subForm[key] = imgs
    },
    handleAvatarSuccess (e, file) {
      console.log(file)
    },
    /**
     * @method 获取经纬度
     */
    getLatLng (latLng) {
      this.subForm.latitude = latLng.lat
      this.subForm.longitude = latLng.lng
    },
    toAddDel (index, key = 0) {
      if (key === 1) {
        this.subForm.service_tag.splice(index, 1)
      } else {
        if (!this.subForm.service_tag[index].title) {
          this.$message.error(`请输入服务标签`)
          return
        }
        this.subForm.service_tag.push({ title: '' })
      }
    },
    /**
     * @method 验证表单值是否正确
     */
    validateForm (formName) {
      let result
      this.$refs[formName].validate(valid => {
        if (valid) {
          result = true
          return true
        } else {
          result = false
          return false
        }
      })
      return result
    },
    /**
     * @method 提交信息
     */
    async submitCompanyInfo () {
      let formArr = ['basicForm', 'relevantForm', 'imgForm']
      if (this.base_plug.banquet_auth) {
        formArr.push('banquetForm')
      }
      let isAllPass = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        if (!this.validateForm(formArr[i])) {
          isAllPass = false
        }
      }
      if (isAllPass) {
        let subForm = JSON.parse(JSON.stringify(this.subForm))
        this.imgArr.map(item => {
          subForm[item] = subForm[item] && subForm[item].length > 0 ? subForm[item][0].url : ''
        })
        subForm.culture = subForm.culture.length > 0 ? subForm.culture.map(item => {
          return item.url
        }) : ''
        let { banquet_mobile_code: mobileCode, banquet_mobile: mobile } = subForm
        subForm.banquet_mobile = mobileCode ? `${mobileCode} - ${mobile}` : mobile
        subForm.service_tag = subForm.service_tag.map(item => {
          return item.title
        })
        let { id } = subForm
        delete subForm.banquet_mobile_code
        delete subForm.id
        let isW7 = this.$store.getters.isW7 === true ? '&' : '?'
        let { code } = id > 0
          ? await this.$api.editCompany(`${isW7}company_id=${id}`, {
            data: subForm
          })
          : await this.$api.addCompany({ data: subForm })
        if (code === 200) {
          this.$message.success(this.$t('tips.successRev'))
          this.$router.back(-1)
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-company-add {
  width: 100%;
  .page-main {
    .el-input,
    .el-select {
      width: 300px;
    }
    .basic-form {
      .avatar-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 128px;
        height: 128px;
      }
      .avatar-uploader:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 128px;
        height: 128px;
        line-height: 128px;
        text-align: center;
      }
      .avatar {
        width: 128px;
        height: 128px;
        display: block;
      }
    }
    .relevant-form {
      width: 900px;
      padding-left: 80px;
      .el-input,
      .el-input-number {
        width: 200px;
      }
      .getLocation {
        margin-top: 5px;
      }
    }
  }
}
</style>
